package com.senseuni.da.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by engine100 on 2018-12-07 12:00:53.
 */
public abstract class AbsRecyclerAdapter<T, V extends RecyclerView> extends RecyclerView.Adapter<ViewHolder> {
    protected Context mContext;
    protected List<T> mDataList;
    protected V mRecyclerView;

    public AbsRecyclerAdapter(V recyclerView, List<T> dataList) {
        mRecyclerView = recyclerView;
        mContext = recyclerView.getContext();
        mDataList = dataList;
        if (mDataList == null) {
            mDataList = new ArrayList<>(1);
        }
    }

    @LayoutRes
    public abstract int getItemLayout();

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(mContext).inflate(getItemLayout(), viewGroup, false);
        return ViewHolder.create(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) {
        T data = mDataList.get(i);
        onBindData(viewHolder, data, i);
    }

    public abstract void onBindData(@NonNull ViewHolder viewHolder, T data, int position);

    @Override
    public int getItemCount() {
        int count =  mDataList == null ? 0 : mDataList.size();
        return count;
    }

    public void replaceData(List<T> newData) {
        mDataList.clear();
        if (newData != null) {
            mDataList.addAll(newData);
        }
        notifyDataSetChanged();
    }

    public void addMoreData(List<T> newData) {
        if (newData != null) {
            mDataList.addAll(newData);
        }
        notifyDataSetChanged();
    }

    public void addMoreData(T newData) {
        if (newData != null) {
            mDataList.add(newData);
        }
        notifyDataSetChanged();
    }

    public void clearData() {
        mDataList.clear();
        notifyDataSetChanged();
    }

    public void remove(int position) {
        if (mDataList.size() > position) {
            mDataList.remove(position);
        }
    }
}

